package com.lmk.ms.common.net.udp.server;

import com.lmk.ms.common.net.udp.server.service.UdpServerService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP 服务端
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public class UdpServer {

    /** 监听端口 */
    private int port;

    /** 服务端业务服务 */
    private UdpServerService ss;

    public UdpServer(int port, UdpServerService ss) {
        this.port = port;
        this.ss = ss;
    }

    public void run(){
        DatagramSocket socket = null;
        try{
            socket = new DatagramSocket(port);

            log.debug("服务端启动完成，开始监听：{}", port);

            byte[] buffer = new byte[200]; // 缓存数组
            DatagramPacket receivePacket = null;
            while (true){
                // 接收数据请求
                receivePacket = new DatagramPacket(buffer, buffer.length);
                socket.receive(receivePacket);

                // 处理接收到的数据
                ss.handel(socket, receivePacket);
            }
        } catch (IOException e) {
            log.error("服务端异常：", e);
        } finally {
            if(socket != null){
                log.debug("关闭服务端...");
                socket.close();
            }
        }
        log.debug("服务端退出");
    }
}
